import { Label, ScrollView } from 'cc';
import { _decorator, Component, Node } from 'cc';
import UtilTool from '../../tools/UtilTool';
import { App } from '../../App';
import { Button } from 'cc';
import { Prefab } from 'cc';
import { instantiate } from 'cc';
import { find } from 'cc';
import AbstractComponent from '../../base/AbstractComponent';
import { EventConst } from '../../common/Common';
import { PD } from '../../player/PlayerData';
import { loadCommonPreFab, showErrorTip, showTipBox } from '../../tools/PopuUp';
import { MultiRoom } from './MultiRoom';
import { MultiMsgMgr } from './MultiMsgMgr';
import { JoinTipWnd } from './JoinTipWnd';
import { MultiRule } from './MultiRule';
import { RoomCreateLayer } from './RoomCreateLayer';
import { JoinItem } from './JoinItem';
import { LoadMg } from '../../tools/LoadMg';
import { UITransform } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('RoomJoinLayer')
export class RoomJoinLayer extends AbstractComponent {

    @property(Label)
    label_wait_tip : Label = null // 等待房主开始的...tip

    @property(Label)
    label_reward : Label = null; // 奖金

    @property(Label)
    label_ticket : Label = null; // 门票
    
    @property(Label)
    label_room_tip : Label = null; // 房间信息

    @property(Label)
    label_join_state : Label = null; // 参赛状态

    @property(Button)
    btn_start : Button = null; // 开始按钮

    @property(Button)
    btn_join : Button = null; // 参赛按钮

    @property(Button)
    btn_back : Button = null; // 退出按钮

    @property(Button)
    btn_set : Button = null; // 设置按钮

    @property(ScrollView) 
    scroll : ScrollView = null;

    @property(Node) 
    memberContentNode : Node = null; // 成员列表父节点

    @property(Prefab)
    joinItemPrefab : Prefab = null; // 成员列表item

    data = null; // 列表数据

    isMaster : boolean = false; // 是否是房主
    isJoin : boolean = false; // 是否已经加入   

    isFromGame : boolean = false; // 是否是游戏进来的
    exitType : number = 1; // 退出类型 0再次挑战 1正常退出, 这个是游戏进来时传过来的参数

    roomType = 0; // 房间类型

    scrollH = 0 // 滚动视图高度

    onLoad() {
        UtilTool.setSize(this.memberContentNode, 3, [0, 2])
        this.scrollH = this.memberContentNode.getComponent(UITransform).height

    }

    start() {

        MultiMsgMgr.getInstance() // 初始化消息监听, 断线重连时需要用到

        App.Event.on(EventConst.ROOM_INFO_UPDATE, this.onRoomInfoUpdate, this) // 房间信息更新事件监听
        App.Event.on(EventConst.ROOM_DESTROY, this.onRoomDestroy, this) // 房间销毁事件监听
        App.Event.on(EventConst.ROOM_KICK_OUT, this.onRoomKickOut, this) // 被踢出房间事件监听

        // 如果是游戏进来的，重新挑战的情况显示参赛界面
        if(this.isFromGame && this.exitType == 0) {
            if(!this.isMaster) {
                this.showJoinTipWnd()
            }
        }

        // 开始按钮，防止连续点击
        App.onClick.addButtonClickEvent(this.btn_start.getComponent(Button), async(param) =>{
            this.onBtnStart()
        }, this,null,true,null,null,1000);

        App.WSGameStatus = 2
    }

    //初始化房间信息 有三种状态：1.我是房主 2.我已参赛 3.我未参赛
    initData(data, roomType, isFromGame=false, exitType=1) {
        // test data
        // data = {
        //     houseOwnerAccount : "123456", // 房主
        //     playAmount : 100, // 门票
        //     canWatch : true, // 是否可以观战
        //     maxPlayer : 3, // 最大人数
        //     gameType : 0, // 游戏类型
        //     currentReward : 1000, // 当前奖金
        //     roomId : "0001", // 房间号
        //     readToCompletePlayersAccount : ["123456", "123457", "123458", "123459"], // 已参赛的玩家
        //     playersAccount : ["123460", "123461"] // 所有玩家
        // }

        this.roomType = roomType; 
        this.isFromGame = isFromGame;
        this.exitType = exitType;

        this.data = data;

        this.label_reward.string = data.currentReward;
        this.label_ticket.string = data.playAmount;

        
        let infoText = UtilTool.formatStr(App.language.getLanguageLab(2034), UtilTool.getRoomNumStr(data.roomId), data.maxPlayer)

        // 房间信息 格式：多人台球（001房-5人场）
        if(data.gameType == 0) {
            this.label_room_tip.string = UtilTool.formatStr("%s %s", App.language.getLanguageLab(116), infoText)
        } else {
            this.label_room_tip.string = UtilTool.formatStr("%s %s", App.language.getLanguageLab(117), infoText)
        }

        // let myAcount = "1234561"
        let myAcount = PD.user.addressUrl // 我的账号
        if(data.houseOwnerAccount === myAcount) {
            this.isMaster = true;
        }

        this.btn_start.node.active = this.isMaster; // 只有房主才显示开始按钮 
        this.isJoin = data.readToCompletePlayersAccount.includes(myAcount) // 是否已经参赛
        if(this.isJoin) {
            this.label_join_state.string = App.language.getLanguageLab(126)
        } else {
            this.label_join_state.string = App.language.getLanguageLab(125)
        }
        this.btn_join.interactable = !this.isJoin;
        find("img", this.btn_join.node).active = !this.isJoin; // 已参赛时，只显示文本已参赛
        find('label', this.btn_join.node).getComponent(Label).fontSize = !this.isJoin ? 36 : 52;

        // 初始化加入的成员列表
        this.memberContentNode.removeAllChildren()

        // 滚动视图设置
        let allH = data.playersAccount.length * 186
        let H = this.scrollH
        if (H<allH){
            H = allH
        }
        this.memberContentNode.getComponent(UITransform).height = H
        if (this.scrollH < allH){
            this.scroll.scrollToBottom()
        }
        else{
            this.scroll.scrollToTop()
        }

        for(let i=0; i<data.playersAccount.length; i++) {
            let member = data.playersAccount[i];
            let item = instantiate(this.joinItemPrefab);

            let isMine = member == myAcount;
            let isHasReady = data.readToCompletePlayersAccount.includes(member); // 是否已经参赛

            item.getComponent(JoinItem).initData(member, data.houseOwnerAccount, this.isMaster, isMine, isHasReady, data.nicknameMap[member]);
            item.parent = this.memberContentNode;
        }

        // 退出的按钮 (如果不是房主，但又已经参赛时，需要隐藏退出按钮)
        if(!this.isMaster && this.isJoin) {
            this.btn_back.node.active = false
        } else {
            this.btn_back.node.active = true
        }

        // 不是房主时，显示等待房主开始的...tip
        this.label_wait_tip.node.active = !this.isMaster;
        if(!this.isMaster) {
            UtilTool.showTextWaitAction(this.label_wait_tip, App.language.getLanguageLab(122))
        }

        this.btn_set.node.active = this.isMaster; // 只有房主才显示设置按钮
        
    }

    // 房间重连设置数据
    initReconnectData(data, roomType, isFromGame=false, exitType=1) {
        this.initData(data, roomType, isFromGame, exitType)
    }

    // 房间信息更新
    onRoomInfoUpdate(data) {

        let isBeMaster = data.houseOwnerAccount == PD.user.addressUrl

        // 成为房主, 弹出提示框
        if(!this.isMaster && isBeMaster) {

            // 如果已经显示了参赛弹窗，就自动关闭了
            let joinTipWnd = find("JoinTipWnd", this.node)
            if(joinTipWnd) {
                joinTipWnd.getComponent(JoinTipWnd).close()
            }

            showTipBox({content: App.language.getLanguageLab(2026)}) // 提示恭喜成为房主框
        }

        this.initData(data, this.roomType, this.isFromGame, this.exitType)
    }

    // 房间销毁
    onRoomDestroy(data) {

        let tipData = {
            content : App.language.getLanguageLab(2031),
            func : (btnIndex) => {
                this.close()
            }
        }
        
        showTipBox(tipData) // 提示房间已经解散框

    }

    // 被踢出房间
    onRoomKickOut(data) {
        let tipData = {
            content : App.language.getLanguageLab(2030),
            func : (btnIndex) => {
                this.close()
            }
        }

        showTipBox(tipData) // 提示被移除房间框
    }

    // 关闭时发送房间列表刷新事件
    close() {
        App.Event.emit(EventConst.ROOM_LIST_REFRESH) // 发送刷新房间列表事件
        this.node.destroy();
    }

    // 参加
    async onBtnJoin() {
        UtilTool.printLog("onBtnJoin");

        this.playClickAudio()
        
        this.showJoinTipWnd()
    }

    // 显示参赛弹窗界面
    async showJoinTipWnd() {

        let joinNode = find("JoinTipWnd", this.node)
        if(!joinNode) {
            joinNode = await loadCommonPreFab('prefabs/hall/multiplay/JoinTipWnd', this.node)
        }

        joinNode.getComponent(JoinTipWnd).initData(this.data.currentReward)
    }

    // 房主的开始按钮
    onBtnStart() {
        UtilTool.printLog("onBtnStart");

        this.playClickAudio()

        MultiMsgMgr.getInstance().sendRoomStart()
        .then((data) => {
            UtilTool.printLog("test start room", data);
            
            if(data.result == 0) {
                UtilTool.printLog("test start room success");
                LoadMg.showLoad({type:1}) // 等待服务端下发开始游戏的消息
            } else {
                showErrorTip(data.result)
            }

        })

    }

    onBtnTest() {
        let that = this

        let canvas = find("Canvas")
        UtilTool.printLog(canvas)
    }

    // 显示规则
    async onBtnQuestion() {
        this.playClickAudio()
        let node = await loadCommonPreFab("prefabs/hall/multiplay/multiRule", null)
        node.getComponent(MultiRule).setGameType(this.data.gameType)
    }

    // 显示房间的设置
    async onBtnSet() {
        UtilTool.printLog("onBtnSet");

        this.playClickAudio()

        let node = await loadCommonPreFab('prefabs/hall/multiplay/RoomCreateLayer', this.node, false)
        node.getComponent(RoomCreateLayer).initModifyUi(this.data, this.roomType, this.isMaster)
    }

    protected onDestroy(): void {
        App.WSGameStatus = 0
        App.Event.off(EventConst.ROOM_INFO_UPDATE, this.onRoomInfoUpdate, this)
        App.Event.off(EventConst.ROOM_DESTROY, this.onRoomDestroy, this)
        App.Event.off(EventConst.ROOM_KICK_OUT, this.onRoomKickOut, this)
    }

    // 退出房间
    onBtnBack() {

        this.playClickAudio()

        let callback = (btnIndex) => {
            // 确定退出房间
            if(btnIndex == 0) {
                MultiMsgMgr.getInstance().sendRoomExit()
                .then((data) => {
                    
                    if(data.result == 0) {
                        this.close()
                    } else {
                        console.error("退出房间失败", data.result);
                        showErrorTip(data.result)
                    }
                })
            }
        }

        showTipBox({content: App.language.getLanguageLab(2028), func:callback, btnType:4}) // 提示退出框

    }

}

